package com.zhitan.netty.server;

import com.zhitan.netty.ChannelRepository;
import com.zhitan.netty.bean.NettyMessage;
import com.zhitan.netty.service.INettyServerHandlerService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * netty服务端处理器
 **/
@Slf4j
@ChannelHandler.Sharable
@Component
@AllArgsConstructor
public class NettyServerHandler extends SimpleChannelInboundHandler<NettyMessage> {

    @Resource
    private final INettyServerHandlerService handlerService;

    /**
     * 有客户端连接服务器会触发此函数
     *
     * @param ctx 通道上下文
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = inSocket.getAddress().getHostAddress();
        int clientPort = inSocket.getPort();
        ChannelId channelId = ctx.channel().id();
        log.debug("客户端【{}】连接Netty服务器[IP:{}:{}]", channelId, clientIp, clientPort);
        log.debug("连接通道数量:{}", ChannelRepository.getLocalConnectCount());
    }

    /**
     * 有客户端终止连接服务器会触发此函数
     *
     * @param ctx 通道
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        ChannelRepository.closeAndClean(ctx);
    }

    /**
     * 有客户端发消息会触发此函数
     *
     * @param ctx          通道
     * @param nettyMessage 消息
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, NettyMessage nettyMessage) throws InterruptedException {
        handlerService.handler(ctx, nettyMessage);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        String socketString = ctx.channel().remoteAddress().toString();
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                log.debug("Client: " + socketString + " READER_IDLE 读超时");
                ctx.disconnect();
            } else if (event.state() == IdleState.WRITER_IDLE) {
                log.debug("Client: " + socketString + " WRITER_IDLE 写超时");
                ctx.disconnect();
            } else if (event.state() == IdleState.ALL_IDLE) {
                log.debug("Client: " + socketString + " ALL_IDLE 总超时");
                ctx.disconnect();
            }
        }
    }

    /**
     * 发生异常会触发此函数
     *
     * @param ctx   通道信息
     * @param cause 异常原因
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ChannelRepository.closeAndClean(ctx);
    }
}
